<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>流程式菜单</title>
  <link rel="stylesheet" href="__SKIN__/js/layui/css/layui.css">
  <link rel="stylesheet" href="__SKIN__/jsplumb/css/jquery-ui.min.css">
<!--  <script src="__SKIN__/js/jquery.js"></script>-->
  <script src="__SKIN__/jsplumb/js/jquery.js"></script>

  <script src="__SKIN__/js/layui/layui.js"></script>

  <script src="__SKIN__/jsplumb/js/jsplumb.min.js"></script>

  <script src="__SKIN__/jsplumb/js/jquery-ui.js"></script>
  <style>
    html,body{height:100%;overflow:hidden;}
    .absolute {
      position: absolute;

    }
    .relative {
      position: relative;
    }
    #flow_box {
      padding: 20px;
      width: 100%;
      height: 1024px;
      border: 1px solid #808080;
      background-image:linear-gradient(to right top , #FFF, #7AFFAF);
    }
    .item {
      font-weight:bolder;
      background-image:linear-gradient(to right bottom, rgba(7, 255, 232, 0.26), rgba(198, 93, 93, 0.26));
      background-color: #7A88FF;
      color:#fff0b7;
      border:1px solid;
      font-size: 12px;
      line-height: 40px;
      width:80px;
      height:40px;
      text-align: center;
    }
    .item-default{
    }
    .item-Round{
      margin: auto;
      border-radius:50%;
    }
    .item-Rhombic{
      -webkit-transform:skew(-20deg);
      -moz-transform:skew(-20deg);
      -o-transform:skew(-20deg);
      -ms-transform:skew(-20deg);
      transform:skew(-20deg);
    }
    .tool{
      display:none;
      width:120px;
      /*width:calc(100%-40px);*/
      left: 92%;
      top: 5%;
    }
    #but{
      left: 84%;
      top: 1%;
    }
    #mouse-menu{
      display: none;
      z-index: 999;
      background-image:linear-gradient(to right top , rgba(24, 53, 243, 0.99), rgba(66, 130, 92, 0.99));
      border-bottom:black 1px solid ;
    }
    #mouse-menu li{
      width:60px;
      height: 30px;
      color:#fff;
      line-height: 30px;
      border-top: black 1px solid;
    }
    #editBox{
      border-radius:3%;
      display: none;
      position: absolute;
      top:50%;
      left: 50%;
      width:500px;
      height:350px;
      background-color: white;
    }
    .closebox{
      border-radius:1%;
      position: relative;
      top:5px;
      left:calc(100% - 55px);
      width:50px;
      height:32px;
      text-align: center;
      line-height: 32px;
    }
    .close{
      width: 100%;
      height: 100%;
      display: block;
    }
    .layui-tab{
      width: 100%;
      position: absolute;
      top:5px;
      left:0;
    }
    #saveUrl{
      left: calc(100% - 67px);
    }
  </style>
</head>

<body>
<!--<div class="layui-container">-->

  <div class="layui-row">
<!--    <div class="layui-col-lg10 layui-col-md12" id="div_go">-->
      <div id="flow_box_outside">
        <div id="flow_box">

        </div>
      </div>
      <div id="but" class="absolute">
         <button data-method="edit" data-type="t" class="layui-btn layui-btn-normal">菜单列表</button>
         <button data-method="save" data-type="s" class="layui-btn layui-btn-normal">保存</button>
      </div>
      <ul id="mouse-menu">
        <li onclick="action.openEdit()">
          <lable>编辑</lable>
        </li>
        <li>
          <lable>删除</lable>
        </li>
      </ul>
      <div id="tool" class="layui-col-lg2 layui-col-md12 tool absolute" >
        <div class="layui-collapse" lay-filter="divCenter" id="right_menu" >
          <div class="layui-colla-item">
            <ul id="menu_list">

            </ul>
          </div>
        </div>
      </div>

      <div id="editBox" class="absolute ">
        <div class="closebox">
          <button type="button" onclick="action.closeEdit()" class="close layui-btn layui-btn-danger layui-btn-sm">关闭</button>
        </div>
        <div class="layui-tab">
          <!--选项卡-->
          <ul class="layui-tab-title">
            <li class="layui-this">形状</li>
            <li>颜色</li>
            <li>跳转地址</li>
          </ul>
          <!--选项卡end-->
          <!--内容-->
          <div class="layui-tab-content">
            <!--形状-->
            <div class="layui-tab-item layui-show">
              <div class="layui-form-item layui-form">
                <div class="layui-inline">
                  <label class="layui-form-label">修改形状</label>
                  <div class="layui-input-inline">
                    <select name="shape" lay-verify="required" id="shape" lay-search="" lay-filter="shape">
                      <option value="">选择形状</option>
                      <option value="item-default">长方形（默认）</option>
                      <option value="item-Rhombic">菱形</option>
                      <option value="item-Round">圆</option>
                    </select>
                  </div>
                </div>
              </div>
            </div>
            <!--形状end-->
            <!--颜色-->
            <div class="layui-tab-item">
              <div class="layui-form-item layui-form">
                <div class="layui-form-item">
                  <label class="layui-form-label">背景颜色</label>
                  <div class="layui-inline" style="left: -11px;">
                    <div id="bgcolor"></div>
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">字体颜色</label>
                  <div class="layui-inline" style="left: -11px;">
                    <div id="ftcolor"></div>
                  </div>
                </div>
              </div>
            </div>
            <!--颜色end-->
            <!--跳转地址-->
            <div class="layui-tab-item">
              <div class="layui-collapse" lay-accordion="" lay-filter="link">
                <div class="layui-colla-item">
                  <h2 class="layui-colla-title">站外跳转地址</h2>
                  <div class="layui-colla-content layui-show">
                    <div class="layui-form-item layui-form" lay-filter="http">
                      <div class="layui-inline">
                        <label class="layui-form-label">全网址</label>
                        <div class="layui-input-inline">
                          <input type="text" id="url" name="url" lay-verify="url" autocomplete="off" placeholder="请输目标网址" class="layui-input">
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="layui-colla-item">
                  <h2 class="layui-colla-title">站内跳转地址</h2>
                  <div class="layui-colla-content">
                    <div class="layui-form-item layui-form" lay-filter="tp">
                      <div class="layui-inline">
                        <label class="layui-form-label">模型</label>
                        <div class="layui-input-inline">
                          <input type="text" id="module" name="module" lay-verify="Url" autocomplete="off" placeholder="请输目标网址" class="layui-input">
                        </div>
                      </div>
                      <div class="layui-inline">
                        <label class="layui-form-label">控制器</label>
                        <div class="layui-input-inline">
                          <input type="text" id="controller" name="controller" lay-verify="Url" autocomplete="off" placeholder="请输目标网址" class="layui-input">
                        </div>
                      </div>
                      <div class="layui-inline">
                        <label class="layui-form-label">方法</label>
                        <div class="layui-input-inline">
                          <input type="text" id="action" name="action" lay-verify="Url" autocomplete="off" placeholder="请输目标网址" class="layui-input">
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <button type="button" class="layui-btn layui-btn-sm relative" id="saveUrl">保存链接</button>
            </div>
            <!--跳转地址end-->
          </div>
          <!--内容end-->
        </div>
      </div>
    </div>

<!--  </div>-->

<!--</div>-->
  <!--jsplumb 封装方法-->
  <script>
    var action  = {
      //jsplumb对象
      obj: {},
      //是否为链接来源  --默认不接受链接
      isSource:false,
      //是否为链接目标
      isTarget:false,
      //是否允许再次拖动连线
      connectionsDetachable:false,
      //分支链接数量  -1为无限制
      maxConnections:-1,
      // 可否编辑    --默认不可编辑
      change:false,
      //html标签标题可否编辑
      contenteditable:false,
      //样式模式  0原始-1图标
      style:0,
      //初始化的数据集
      data:{},
      //当前打开的编辑对象id
      edit: {},
      //当前新增的方块数
      num:0,
      //节点关系
      process:{},
      //端点形状
      endpoint:["Dot", { radius: 3 }],
      //连线配置  Bezier: 贝塞尔曲线 || Flowchart: 具有90度转折点的流程线 || StateMachine: 状态机 || Straight: 直线
      connector:['Flowchart',{ stub: [0, 0], gap: 10, cornerRadius: 5, alwaysRespectStubs: true }],
      //端点（箭头）样式  Arrow 一个可配置的箭头 || Label 标签，可以在链接上显示文字信息 || PlainArrow 原始类型的箭头 || Diamond 菱形箭头 || Custom 自定义类型
      overlays:[['Arrow',{width:10,length:10,location:1}]],
      //链接线样式
      connectorPaintStyle:{strokeStyle: "#1e8151",stroke: '#000000', fillStyle: "transparent", radius: 2, lineWidth: 2,strokeWidth: 1},
      //悬浮在连线上的样式
      connectorHoverStyle:{stroke: 'rgba(151,171,231,0)',strokeStyle: "#216477", strokeWidth: 3 ,outlineColor: "white"},
      //端点的样式
      paintStyle:{fillStyle: "#000000",radius: 0,stroke: '#000000',lineWidth: 2,lineWidth:1, strokeWidth: 2},
      //悬停端点时的样式
      hoverPaintStyle:{ stroke: '#000000', strokeWidth: 3 },
      //终点样式
      endpointStyle:{ fill: 'rgba(9,9,9,0.18)',outlineStroke: 'rgb(5,5,5)', outlineWidth: 2 },
      //终点悬停样式
      endpointHoverStyle:{fillStyle: "#ffffff", strokeStyle: "#ffffff"},
      //链接样式
      connect:{},

      /**
       * 初始化
       */
      init:function(type,option,config=''){
        this.change = config.change ? true : false;
        this.isSource = config.isSource ? true :false; //能否发起
        this.isTarget = config.isTarget ? true :false; //能否接收
        this.connectionsDetachable=config.connectionsDetachable ? true :false; //允许拉好的连线再次拖动
        this.contenteditable=config.contenteditable ? true :false; //允许拉好的连线再次拖动
        this.maxConnections=config.maxConnections ? config.maxConnections : 1; //允许拉好的连线再次拖动
        if(type === 'create'){
          //拖拽创建
          var data = option.data;  //data=ui
          this.createModel(data.ui,data.selector)
        }else if(type === 'init'){
          //页面初始化
          if(option.length!=0){
            $.each(option,function(n,m){
              action.createModel(m);
            });
          }

          this.circular_link();
        }

      },
      /**
       *设置链接属性
       */
      setConnect:function(e){
        //初始化连线样式
        jsPlumb.importDefaults(
          {
            isSource: this.isSource,
            isTarget: this.isTarget,
            Anchors:['Right','Left'],
            Endpoint: this.endpoint,    //端点
            EndpointStyle: this.endpointStyle,          //端点样式
            Connector: this.connector,  //连线的容器
            Overlays: this.overlays,    //连接线和端点的遮罩层样式
            ConnectorStyle : this.connectorPaintStyle,  //链接线样式
            ConnectorHoverStyle : this.connectorHoverStyle,  //悬浮在连线上的样式
            PaintStyle : this.paintStyle,  //连线样式
            HoverPaintStyle : this.hoverPaintStyle,  //鼠标经过链接线时的样式
            EndpointHoverStyle : this.endpointHoverStyle,   // [源端点鼠标经过样式，目标端点鼠标经过样式]
            MaxConnections: this.maxConnections,    // 端点最大连接线数量默认为1， 设置成-1可以表示无数个链接
            ConnectionsDetachable: this.connectionsDetachable,
          }
        );

        //初始化可否拖拽
        this.connect={
          isSource: this.isSource,
          isTarget: this.isTarget,
          uuids: ['right_'+e, 'left_'+e]
        }
      },
      /**
      * 获取页面元素数量，判断新增id值
      */
      setnum:function(){
        let a = $('#flow_box').children("div");
        if(a.length>0){
          //页面已有块 --判断最大ID值并获取赋予this.num
          let array = [];
          for (var i=0;i<a.length;i++){
            array.push(a[i].id.substr( a[i].id.lastIndexOf("_")+1) );
              // array.push(a[i].id);
          }
          this.num = this.getmax(array); //动态添加最大ID
        }else{
          //页面没有块
          this.num = 0;
        }
      },
      /*
      * 判断数组中最大值
      * @x 数组
      */
      getmax:function(x){
        var max = parseInt(x[0]);    //首先定义第一个数为最大数
        if (x.length<2) {return max;}
        for (var i = 0; i<x.length; i++) {
          if(parseInt(x[i])>max){max=parseInt(x[i]);}}
        return max;
      },
      /**
       * 拖拽创建页面模型（方块）
       * @ui 拖拽的块对象
       * @selector 放置区域对象
       */
      createModel:function(ui, selector){
        if(selector){
          this.setnum();
          this.num++;
          var id = "model_" + this.num;
          var uuid = this.num;
          var class_p = $(ui.helper).attr("class");  //模块的所有class

          var data = $(ui.helper).data();  //模块的所有data值
          var data_type = data.type||data.type; //是否自定义
          var data_id = data.id||data.id;  //菜单id
          var data_action = data.action||data.action;   //链接地址

          var name = $(ui.draggable).html();
          var arr = class_p.split(' ');
          var class_n = 'item-default';
          var left = parseInt(ui.offset.left - $(selector).offset().left);
          var top = parseInt(ui.offset.top - $(selector).offset().top);
          var style = {id:id,style:{left:left,top:top}};
        }else{
          var selector = $('#flow_box')[0];
          var id = "model_" + parseInt(ui.id);
          var uuid = parseInt(ui.id);
          var name = ui.name;
          var class_n = ui.class_n;
          var left = ui.style.left;
          var top = ui.style.top;
          var data_action = ui.action;
          if(ui.to_id != undefined){
            let e = [];
            if(action.isArray(ui.to_id)){
              for(var l in ui.to_id){
                e[l] = [parseInt(ui.id),parseInt(ui.to_id[l])];
              }
            }else{
              e = ui.to_id;
            }
            this.process[parseInt(ui.id)] = e;
          }
          var style= {id:id,style:ui.style};
        }
        //页面放置元素
        let html  = '';
            html += '<div class="'+class_n+' item" data-class="'+class_n+'" data-action="'+data_action+'" contenteditable="'+this.contenteditable+'" id="' + id +'"  >'+name+'</div>';
        $(selector).append(html);
        this.set_style(style); //加载样式
        this.setConnect(uuid);
        if(this.change==true){  //不可编辑状态
          this.add_middle(uuid);   //集体添加端点
          this.draggable(id);    //控制拖拽
          this.onEvent(id);      //绑定事件群

        }
        return id;
      },
      /**
       * n方块ID，m是样式串 {top: "300px", left: "150px"}
       * 赋予独立样式属性
       */
      set_style:function(e){
        $('#'+e.id).css('position','absolute');
        $.each(e.style,function(n,m){
          $('#'+e.id).css(n,m);
        })
      },
      /**
       * 设置节点
       */
      act:function(z,x){
        if (typeof(x)==='number'){
          let node = {
            source: 'model_'+z,
            target: 'model_'+x,
            DragOptions: { cursor: 'pointer', zIndex: 2000 }
          };
          jsPlumb.connect(node,this.connect);
        }
      },
      /**
       * 循环链接
       */
      circular_link:function(){
        //循环链接
        $.each(this.process,function(n,m){
          if(action.isArray(m)){
            if(m.length>0){
              $.each(m,function (k,v) {
                action.act(v[0],v[1]);
              })
            }
          }else{
            action.act(n,m);
          }
        })
      },
      /**
       * 集体添加端点
       */
      add_middle:function(e){
          jsPlumb.addEndpoint('model_'+e,{ anchor: 'RightMiddle',uuid:'right_'+e }, this.connect);
          jsPlumb.addEndpoint('model_'+e, { anchor: 'LeftMiddle',uuid:'left_'+e }, this.connect);
          // jsPlumb.addEndpoint(e, { anchor: 'TopCenter' }, this.connect);
          // jsPlumb.addEndpoint(e, { anchor: 'BottomCenter' }, this.connect);
      },
      /**
       * 控制拖拽
       */
      draggable:function(e){
        jsPlumb.draggable(e);  //拖拽控制
      },
      /**
       * 判断是否为数组
       * @param o
       * @return {boolean}
       */
      isArray:function(o){
        return Object.prototype.toString.call(o)== '[object Array]';
      },
      /**
       * 注册双击编辑文本事件
       */
      onEvent(e){
        //在div内部屏蔽系统默认的鼠标右键事件
        $("div").bind("contextmenu", function(){
          return false;
        })
        $('#'+e).on(
          {
            //鼠标移入
            mouseover:function(){
                // console.log($(this).attr('id'));
            },
            //鼠标移出
            mouseout:function(){
               // console.log($(this).attr('id'));
            },
            //单击事件
            click:function(){
              $(this).draggable({ disabled: false });
            },
            //鼠标控制
            mousedown:function(e){
              if (3 == e.which) {
              //右键为3 触发编辑框
                $(this).attr({ contenteditable: false });
                action.editWindow(this,e);
              } else if (1 == e.which) {
                //左键为1 暂定--跟单击相似？
              }
            },
            //双击
            dblclick:function (){
              $(this).attr({ contenteditable: true });
              $(this).draggable({ disabled: true });
            }
          })
        },
      /**
       * 右键菜单列表
       */
      editWindow(d,e){
        this.edit = d; //修改当前正在编辑的元素
        $('#mouse-menu').show().menu({
          position:{my:'left top',at:'right top'}
        }).
        css('position','absolute').
        css('left',e.pageX).
        css('top',e.pageY);
      },
      /**
       * 打开修改窗
       */
      openEdit:function(){
        let left = $('#flow_box_outside').width()-parseInt($('#editBox').css('width'))-50;
        let top = $('#flow_box_outside').height()-parseInt($('#editBox').css('height'))-100;
        $('#editBox').show().css('left',left+'px').css('top',top+'px');
        $('#mouse-menu').hide();
        this.preloaded(); //预加载数据
      },
      /**
       *  修改窗口关闭事件
       */
      closeEdit:function(){
          $('#editBox').hide();
      },
      /**
       * 修改表单预加载
       */
      preloaded:function(){
        //获取原始值：
        let data = $(action.edit).data();

        setEditVals(data);
      }
    }
  </script>
  <!--plumb实例化-->
  <script>
    /* global jsPlumb */
    jsPlumb.ready(function () {
      getMenu();
      /***单线结构数据样例***/
      var  data = {
        0:{id:1,name:'生产管理',class_n:'item-default',style:{top:'375px',left:'150px'},to_id:[2]},

        1:{id:2,name:'派工单',class_n:'item-default',style:{top:'225px',left:'300px'},to_id:[3]},
        2:{id:3,name:'派工单审批',class_n:'item-default',style:{top:'525px',left:'300px'},to_id:[4]},

        3:{id:4,name:'领料单',class_n:'item-default',style:{top:'150px',left:'450px'},to_id:5},
        4:{id:5,name:'领料单审批',class_n:'item-default',style:{top:'300px',left:'450px'},to_id:6},
        5:{id:6,name:'质检单',class_n:'item-Round',style:{top:'450px',left:'450px'},to_id:7},
        6:{id:7,name:'质检单审批',class_n:'item-default',style:{top:'600px',left:'450px'},to_id:8},

        7:{id:8,name:'商品入库单',action:'http: http://track/admin/Jsplumb/index1/',class_n:'item-Rhombic',style:{top:'75px',left:'600px'},to_id:9},
        8:{id:9,name:'入库审批',action:'tp: admin/Jsplumb/index1',class_n:'item-default',style:{top:'225px',left:'600px'}},
      };
      /***分支结构数据样例***/
      var  aa = {
        0:{id:1,name:'生产管理',class_n:'item-default',style:{top:'375px',left:'150px'},to_id:[2,3]},

        1:{id:2,name:'派工单',class_n:'item-default',style:{top:'225px',left:'300px'},to_id:[4,5]},
        2:{id:3,name:'取料单',class_n:'item-default',style:{top:'525px',left:'300px'},to_id:[6,7]},

        3:{id:4,name:'添加派工单',class_n:'item-default',style:{top:'150px',left:'450px'}},
        4:{id:5,name:'审批派工单',class_n:'item-default',style:{top:'300px',left:'450px'}},
        5:{id:6,name:'添加取料单',class_n:'item-default',style:{top:'450px',left:'450px'}},
        6:{id:7,name:'审批取料单',class_n:'item-default',style:{top:'600px',left:'450px'}}
      };
      //以下data2为ajax获取流程菜单配置的方法
      // let get_url = "{:url('jsplumb/get_data')}";
      // let data2 = ajax(get_url,{id:'{$id}'});
      // console.log(data2);
      // console.log(data);
      /**
       * 初始化页面原始块  init为操作类型，data为数据，后边的3个参数来控制页面元素可否修改 ，
       * 注1：如果要作为展示页面得话页面右上角的两个按钮需要隐藏掉，并且把控制参数变为false即可
       * 注2：暂时删除节点没有做，
       * 注3，页面部分需要遮罩层和窗口关闭逻辑待补全
       * 注4，跳转的话a标签方案行不通，生成jsplumb块的过程中a标签会报错，考虑使用js跳转会合适点，地址信息在每个html元素的data-action属性中保存
       * 注5，右上角菜单的样式我没有添加，哪个地方是用jquery生成的，没有额外渲染，直接添想要的样式就好，非常方便，前些天一个是没想好，另一个是样式太纠结，浪费时间
       */
      action.init('init',data,{isSource:true,isTarget:true,change:true});

      /**
       * jquery-ui拖拽
       */
      $( "#right_menu .brick" ).draggable({
        // revert:true,  //恢复到原位
        helper:"clone",  //拖拽模式 clone-克隆
        scope:"process",
      });

      /**
       * jquery-ui接收 并创建单个jsplumb元素
       */
      $( "#flow_box" ).droppable({
        scope:"process",
        drop: function( event, ui ) {
          action.init('create',{data:{ui:ui, selector:this},},{isSource:true,isTarget:true,change:true});
        }
      });
    })
    //检查是否链接过
    jsPlumb.bind("beforeDrop", function (conn, originalEvent) {
      //查看被连接的两个点间是否已经连接过
      var conns =jsPlumb.getConnections({
        source:conn.sourceId,
        target:conn.targetId
      });
      var connsAnti =jsPlumb.getConnections({
        source:conn.targetId,
        target:conn.sourceId
      });
      console.log(conn);
      console.log(conns);
      //如果大于1条，则不在进行连接
      var a = conns.length
      var b = connsAnti.length
      var c = 0
      if (a>c || b>c) {
        console.log(conns.length)
        return false // 链接不会建立，注意，必须是false
      } else {
        console.log('链接会自动建立')
        return true // 链接会自动建立
      }

    });
    // 请单点击一下连接线
    jsPlumb.bind('click', function (conn, originalEvent) {
      if (window.prompt('确定删除所点击的链接吗？ 输入1确定') === '1') {
        jsPlumb.deleteConnection(conn);
      }
    })
    /*
     * 获取sysmenu的数据
     */
    function getMenu(){
      $.ajax({
        url:"{:url('getmenu')}",
        type:'post',
        dataType:'json',
        data:'',
        success:function(res){
          if (res.code == 200) {
            let html= setMenuList(res.data);
            $('#menu_list').html(html).menu({position:{my:'right top',at:'left top'}});
            $( "#right_menu .brick" ).draggable({
              // revert:true,  //恢复到原位
              helper:"clone",  //拖拽模式 clone-克隆
              scope:"process",
            });
          }
        }
      })
    }
    /*
     * 设置sysmenu的数据
     */
    function setMenuList(e){
      let html = '';
      // console.log(e);
      $.each(e,function (k,v) {
          html += '<li>';
          html += '<a data-type="default" data-id="'+v.id+'" data-action="'+configUrl(v)+'" class="" href="javascript:void(0);">'+v.title+'</a>';
          if(v.hasOwnProperty('children')){
            html += '<ul>';
            $.each(v.children,function (n,m) {
              html += '<li>';
              html += '<a data-type="default" data-id="'+m.id+'" data-action="'+configUrl(m)+'" class="brick" href="javascript:void(0);">'+m.title+'</a>';
              html += '</li>';
            })
            html += '</ul>';
          }
          html += '</li>';
      })
      html += '<li>';
      html += '<a data-type="custom" class="brick" href="javascript:void(0);">自定义</a>';
      html += '</li>';
      return html;
    }
    /*
     * 提取url
     * @param e 单条数据集
     */
    function configUrl(e){
      let action = '';
      if(e.url===undefined || e.url===null || e.url===''){
        if(e.action===undefined || e.action===null || e.action===''){

        }else{
          action +='tp: '+e.module+'/'+e.controller+'/'+e.action;
        }
      }else{
         action += 'http: '+e.url;
      }
      return action;
    }
    /**
     * ajax请求
     * @param url ajax地址
     * @param data 请求参数
     * @param type 1|同步  2|异步
     * @return arr 同步返回数据，异步弹出msg提示信息
     */
    function ajax(url,data,type=1){
      var arr = {};
      if(type = 1){
        async = false;
      }else{
        async = true;
      }
      $.ajax({
        url:url,
        type:'post',
        data:data,
        dataType:"html",
        async: async,//关闭异步
        success:function(e){
          if(type==1){
            arr = eval('(' + e + ')');
          }else{
            alert(e.msg);
          }
        }
      });
      return arr;
    }
    /*
     * 初始化颜色选择器
     * @param id 页面标签的id
     * @param e  颜色拾取器对象
     * @param c  要修改的css属性
     * @param d  初始颜色
     */
    function colorpic(id,e,c,d){
      e.render({
        elem: id
        ,color: d //设置默认色
        ,done: function(color){
          $(action.edit).css(c,color);
        }
        ,change:function(color){
          $(action.edit).css(c,color);
        }
      });
    }
  </script>
  <!--layui-->
  <script>
    $layui = layui.define(['element', 'layer','form','colorpicker'], function(){
      var element = layui.element;
      var layer = layui.layer;
      var form = layui.form;
      var colorpicker = layui.colorpicker;

      //监听折叠
      element.on('collapse(link)', function(data){
        // console.log(data.content);
        // layer.msg('展开状态：'+ data.show);
      });
      //整体的编辑事件
      var active = {
        edit:function(m){
          let state = $('#tool').css('display');
          if(state == 'none'){
            $('#tool').show();
          }else{
            $('#tool').hide();
          }
        },
        save:function (m) {
          var data = $('#flow_box').find('div');
          var param = [];
          var conns = jsPlumb.getConnections();
          $.each(data,function (k,v) {
            var id = $(v).attr('id');//id
            let name = $(v).html(); //name
            let action = $(v).data('action'); //action && class_n
            let class_n = $(v).data('class'); //action && class_n
            let top = $(v).css('top');
            let left = $(v).css('left');
            let color = $(v).css('color');
            let background_color = $(v).css('background-color');
            var to_id = []; //怎么获取
            $.each(conns,function (n,m) {
              if(id == m.sourceId){
                let to_id_arr = m.targetId.split('_');
                to_id.push(to_id_arr[1]);
              }
            })
            let id_arr = id.split('_');
            param.push({id:id_arr[1],name:name,action:action,class_n:class_n,style:{top:top,left:left,color:color,background_color:background_color},to_id:to_id});
          })
          console.log(param);
          let url = "{:url('jsplumb/save_data')}";
           let res = ajax(url,{id:'{$id}',data:param});
           alert(res.msg);
        }
      }
      $('#but .layui-btn').on('click', function(){
        var othis = $(this), method = othis.data('method');
        active[method] ? active[method].call(this, othis) : '';
      });

      //形状选择事件
      form.on('select(shape)', function(obj){
          let data = $(action.edit).data(); //获取寄存的当前class类型
          let class_p = $(action.edit).attr('class'); //获取对象的所有class串
          let newClass = obj.value+' '+class_p.substr(class_p.indexOf(data.class)+data.class.length);
          $(action.edit).attr('class',newClass).attr('data-class',obj.value);
      });

      /**
       * layui外部调用预加载形状下拉
       * @param class_n
       */
      window.setEditVals = function(e){
        //预加载class下拉
        $('#shape').val(e.class);
        form.render('select');
        //初始背景颜色
        colorpic('#bgcolor',colorpicker,'background-color',$(action.edit).css('background-color'));
        //初始字体颜色
        colorpic('#ftcolor',colorpicker,'color',$(action.edit).css('color'));
        //判断有无跳转数据
        if(e.action!=='' || e.action!==undefined || e.action!==null){
          //判断链接种类
          let urlArr = e.action.split(' ');
          if(urlArr[0]==='http:'){
            form.val('http',{
              url:urlArr[1],
            });
          }else if(urlArr[0]==='tp:'){
            let TpArr = urlArr[1].split('/');
            form.val('tp',{
              module:TpArr[0],
              controller:TpArr[1],
              action:TpArr[2],
            });
          }
        }
      }

      //将修改的信息保存入对象
      $('body #saveUrl').on('click',function () {
        let url = $('#url').val();
        let module = $('#module').val();
        let controller = $('#controller').val();
        let index = $('#action').val();
        if(url!==undefined && url!==null && url!==''){
          var  Url_n ='http: '+url;
        }else if(index!==undefined && index!==null && index!==''){
          var  Url_n ='tp: '+module+'/'+controller+'/'+index;
        }else{
          var  Url_n = '';
        }
        $(action.edit).data('action',Url_n);
      });

    });
  </script>
</body>

</html>